/**
 * Copyright (c) 2014-2016 www.nryuncang.com. All Rights Reserved.
 */
package com.topisv.tms.service.prioritySend;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.topisv.tms.entity.ExpressConfigure;
import com.topisv.tms.entity.OfflineEdiOrder;
import com.topisv.tms.utils.ExpressUtil;
import com.topisv.tms.utils.yto.MD5Utils;

import net.sf.json.JSONObject;

/**
 * 
 *  天天快递优先派送订单回传接口
 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
 * @version 1.0.0
 */
public class TTKDEXOrderBackInterfaceService {
	
	private static final Logger logger = LoggerFactory.getLogger(TTKDEXOrderBackInterfaceService.class);
	
	private final static String URL = "http://api.ttk.cn:22220/InterfacePlatform/ApiService";//http://183.136.190.216:22221/InterfacePlatform_test/ApiService
	private final static String APPKEY = "NRYUNCANG";//NRYUNCANG
	private final static String APPSECRT = "3Lt8fUeBV5";//3Lt8fUeBV5
	private final static String WAYBILL_ORDERPUSH = "Waybill_OrderPush";
	private final static String SITE = "总部";
	private final static String CUS = "测试客户";
	private final static String PASSWORD = "1234";
	private final static String CHECKDELIVERY = "false";
	private final static String ISRETURNDATOUBI = "false";
	private final static String ISRETURNBILLCODE = "false";
	private final static String BILLCODETYPE = "天天云仓面单";
	private final static String ECCOMPANYID = "TTYUNCANG";//www.nryuncang.com
	private final static String ORDERTYPE = "1";
	
	
	/**
	 * 
	 * 发送天天快递接口 post，返回请求结果
	 *
	 * @param content
	 * @return
	 * @throws Exception [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	public static String getTTKDEXResult(String params) throws Exception{
		long timestamp = System.currentTimeMillis();
		String content = APPKEY + WAYBILL_ORDERPUSH + params + timestamp + APPSECRT;
		String digest = ExpressUtil.encryptBASE64(MD5Utils.md532(content,"utf-8")).replace("\r\n", "");

		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("params", params));
		parameters.add(new BasicNameValuePair("appKey", APPKEY));
		parameters.add(new BasicNameValuePair("serviceCode", WAYBILL_ORDERPUSH));
		parameters.add(new BasicNameValuePair("digest", digest));
		parameters.add(new BasicNameValuePair("timestamp", String.valueOf(timestamp)));
		
		return doPost(URL, parameters);
	}
	
	/**
	 * 
	 * 发送post请求方法
	 *
	 * @param url
	 * @param parameters
	 * @return
	 * @throws Exception [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	public static  String  doPost(String url, List<NameValuePair> parameters) throws Exception {
		
		StringBuffer sb = new StringBuffer();
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8")));
		
		HttpResponse httpResponse = client.execute(httpPost);
		BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), Charset.forName("UTF-8")));
		String content = null;
		while ((content = reader.readLine()) != null) {
			sb.append(content);
		}
		return sb.toString();
	}
	/**
	 * 
	 * 组装JSON报文
	 *
	 * @param ediOrder
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	public static String getJson(OfflineEdiOrder ediOrder, ExpressConfigure expressConfigure) {
		
		//寄件人信息
		JSONObject sender = new JSONObject();
		
		sender.put("name", ediOrder.getSendna());
		sender.put("phone", "");
		sender.put("mobile", ediOrder.getSendMobile());
		sender.put("prov", ediOrder.getSendProvna());
		sender.put("city", ediOrder.getSendCityna());
		sender.put("area", "");
		sender.put("address", ediOrder.getSendAddres());
		
//		sender.put("name", "能容云仓");
//		sender.put("phone", "");
//		sender.put("mobile", "15178940579");
//		sender.put("prov", "浙江省");
//		sender.put("city", "杭州市");
//		sender.put("area", "");
//		sender.put("address", "滨康路101号海威大厦");
		
		//收件人信息
		JSONObject receiver = new JSONObject();
		
		receiver.put("name", ediOrder.getRecena());
		receiver.put("phone", ediOrder.getTeleph());
		receiver.put("mobile", ediOrder.getMobile());
		receiver.put("prov", ediOrder.getProvna());
		receiver.put("city", ediOrder.getCityna());
		receiver.put("area","");
		receiver.put("address", ediOrder.getAddres());
		
//		receiver.put("name", "张三");
//		receiver.put("phone", "");
//		receiver.put("mobile", "15178940579");
//		receiver.put("prov", "浙江省");
//		receiver.put("city", "杭州市");
//		receiver.put("area", "");
//		receiver.put("address", "滨康路101号海威大厦");

		
		JSONObject data = new JSONObject();
		data.put("txLogisticID", ediOrder.getOrdeno());
		data.put("ecCompanyId", ECCOMPANYID);
		data.put("mailNo", ediOrder.getMailNo());
		data.put("weight", "");
		data.put("codSplitFee", "");
		data.put("buyServiceFee", "");
		data.put("orderType", ORDERTYPE);
		data.put("serviceType", "99");
		data.put("goodsValue", "");
		data.put("itemsValue", "");
		data.put("remark", "");
		data.put("sender", sender);
		data.put("receiver", receiver);
		
//		data.put("txLogisticID", "PD145275768955544");
//		data.put("ecCompanyId", ECCOMPANYID);
//		data.put("mailNo", "997000507920");
//		data.put("weight", "");
//		data.put("codSplitFee", "");
//		data.put("buyServiceFee", "");
//		data.put("orderType", ORDERTYPE);
//		data.put("serviceType", "99");
//		data.put("goodsValue", "");
//		data.put("itemsValue", "");
//		data.put("remark", "测试用例");
//		data.put("sender", sender);
//		data.put("receiver", receiver);
		
		JSONObject json = new JSONObject();
		json.put("site", expressConfigure.getCompanyName());
		json.put("cus", expressConfigure.getWarehouseName());
		json.put("password", expressConfigure.getPassword());
		json.put("checkDelivery", CHECKDELIVERY);
		json.put("isReturnDatoubi", ISRETURNDATOUBI);
		json.put("isReturnBillcode", ISRETURNBILLCODE);
		json.put("billcodeType", BILLCODETYPE);
		json.put("data", data);
		
//		json.put("site", "上海公司市场部");
//		json.put("cus","能容上海仓");
//		json.put("password", "scb123");
//		json.put("checkDelivery", CHECKDELIVERY);
//		json.put("isReturnDatoubi", ISRETURNDATOUBI);
//		json.put("isReturnBillcode", ISRETURNBILLCODE);
//		json.put("billcodeType", BILLCODETYPE);
//		json.put("data", data);
		
		return json.toString();
	}
	
	
	public static void main(String[] args) {
		String jsonStr = getJson(null, null);
		System.out.println("jsonStr:"+jsonStr);
		try {
			String str =getTTKDEXResult(jsonStr);
			System.out.println(str);
			//{"mailNo":"997000507920","datoubi":"","packageName":"","packageCode":"","isDelivery":"true","message":"成功","code":"1000"}
			JSONObject resultJsonObject = JSONObject.fromObject(str);
			System.out.println(resultJsonObject.get("code"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
